using MultiAgentsClient.ChatDataStructures;
using MultiAgentsShared;
using static MultiAgentsClient.Manager.MessageManager;
using static MultiAgentsClient.Manager.ProjectManager;

namespace MultiAgentsClient.Presentation;

public partial record ToolCallConfirmMessageModel
{
    private readonly IEventBus eventBus;

    public ChatMessageData? toolChatMessage = null;
    public IState<bool> IsToolsCheckButtonDisplay => State.Value(this, () => false);

    public ToolCallConfirmMessageModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<ToolCallRequstCommand>(async cmd => { await ToolCallRequstCommandHandler(cmd); });
        eventBus.Subscribe<SendUserMessageCompleteCommand>(async cmd => { await ClosePopup(); });
        eventBus.Subscribe<SwitchChatRoomCompleteCommand>(async cmd => { await ClosePopup(); });
    }

    public async ValueTask ApproveToolCall()
    {
        await IsToolsCheckButtonDisplay.SetAsync(false, default);

        if (toolChatMessage == null)
        {
            return;
        }

        eventBus.Publish(new ToolCallUserConsentCommand(true, toolChatMessage));

        toolChatMessage = null;
    }

    public async ValueTask RefuseToolCall()
    {
        await IsToolsCheckButtonDisplay.SetAsync(false, default);

        if (toolChatMessage == null)
        {
            return;
        }

        eventBus.Publish(new ToolCallUserConsentCommand(false, toolChatMessage));

        toolChatMessage = null;
    }

    private async ValueTask ToolCallRequstCommandHandler(ToolCallRequstCommand cmd)
    {
        toolChatMessage = cmd.ChatMessage;
        await IsToolsCheckButtonDisplay.SetAsync(true);
    }

    private async ValueTask ClosePopup()
    {
        toolChatMessage = null;
        await IsToolsCheckButtonDisplay.SetAsync(false);
    }
}
